package com.base.component.ai.platform.baidu;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import com.base.component.ai.platform.ChatCompletionsHandler;
import com.base.component.ai.platform.core.bo.common.ChatCompletionsBO;
import com.base.component.ai.platform.core.converter.MessageRoleEnum;
import com.base.component.ai.platform.core.utils.Utils;
import com.base.core.head.dto.ai.MessageTextDTO;
import com.gitee.magic.context.ConverterEditorUtils;
import com.gitee.magic.core.json.JsonObject;
import com.gitee.magic.framework.base.rest.HttpRequest;
import com.gitee.magic.framework.base.rest.HttpWrapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author zywei
 *
 */
@ConditionalOnProperty(
		prefix = "base.ai.baidu.wenxin",
		value = {"accessKey","secretKey"})
@Slf4j
@Service
public class WenxinHandler implements ChatCompletionsHandler<MessageTextDTO>{

	private static final String DATA="data: (\\{.*\\})";

    @Value("${base.ai.baidu.wenxin.url:https://aip.baidubce.com}")
	private String url;
    @Value("${base.ai.baidu.wenxin.apiKey}")
    private String apiKey;
    @Value("${base.ai.baidu.wenxin.secretKey}")
    private String secretKey;
    
    private static final String STREAM_URL = "/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
	
	@Override
	public List<String> getSupportModel() {
		return Arrays.asList("wenxin");
	}

	@Override
	public String execute(ChatCompletionsBO<MessageTextDTO> param) {
		WxChatCompletionsAO ao=converterToParam(param);
		ao.setStream(false);
		String requestbody=ConverterEditorUtils.converterObject(ao).toString();

		log.info("model:{} agent :{} request: {}",param.getModel(),param.getCode(),requestbody);
		String accessToken=getAccessToken();
		HttpRequest request=new HttpRequest(url+STREAM_URL);
		request.setUrlParam("access_token", accessToken);
    	request.setHeader(HttpWrapper.CONTENTTYPE,HttpWrapper.CONTENTTYPE_JSON);
    	request.setBodyContent(requestbody);
    	HttpWrapper wrapper=new HttpWrapper();
    	String content=wrapper.start(request);
    	WxChatCompletionsVO vo= ConverterEditorUtils.restoreObject(WxChatCompletionsVO.class, new JsonObject(content));
    	return vo.getResult();
	}

	@Override
	public void execute(ChatCompletionsBO<MessageTextDTO> param, Consumer<String> frameConsumer) {
		WxChatCompletionsAO ao=converterToParam(param);
		ao.setStream(true);
		String requestbody=ConverterEditorUtils.converterObject(ao).toString();

		log.info("model:{} agent :{} request: {}",param.getModel(),param.getCode(),requestbody);
		String accessToken=getAccessToken();
		HttpRequest request=new HttpRequest(url+STREAM_URL);
		request.setUrlParam("access_token", accessToken);
    	request.setHeader(HttpWrapper.CONTENTTYPE,HttpWrapper.CONTENTTYPE_JSON);
    	request.setBodyContent(requestbody);
    	HttpWrapper wrapper=new HttpWrapper();
    	HttpURLConnection connection=wrapper.requestConnect(request);
    	Utils.streamConsumer200(connection, (s)->{
            Matcher matcher = Pattern.compile(DATA).matcher(s);
            while (matcher.find()) {
                String jsonData = matcher.group(1);
                // 现在jsonData包含了"{...}"中的内容，你可以使用JSON库解析它
                WxChatCompletionsVO dto = ConverterEditorUtils.restoreObject(WxChatCompletionsVO.class, new JsonObject(jsonData));
                frameConsumer.accept(dto.getResult());
            }
		});
	}

	private String getAccessToken() {
        HttpRequest request = new HttpRequest(url+"/oauth/2.0/token");
        request.setUrlParam("grant_type", "client_credentials");
        request.setUrlParam("client_id", apiKey);
        request.setUrlParam("client_secret", secretKey);
		request.setHeader(HttpWrapper.CONTENTTYPE, "application/json; charset=UTF-8");
		HttpWrapper wrapper = new HttpWrapper();
		String content = wrapper.start(request);
        String acToken = new JsonObject(content).getString("access_token");
		return acToken;
    }
    
    /**
     * 获取参数
     * @param accessId
     * @param messages
     * @return
     */
    public WxChatCompletionsAO converterToParam(ChatCompletionsBO<MessageTextDTO> param) {
    	WxChatCompletionsAO req=new WxChatCompletionsAO();
		req.setTemperature(param.getTemperature());
		req.setMessages(param.getMessages());
		return req;
    }

	
	public static void main(String[] args) {
		
		String systemPrompt="""
				#角色和关系：
				你的角色为: 婧儿，女，25岁
				你和对方的关系为：恋人
				
				#目标：
				根据提供的这一系列反馈选项，以及角色和关系上下文，再结合聊天记录。针对对方说的最后一句话，选出一个反馈选项列表里面最合适的选项。如果没有合适，不要硬塞！就返回null
				
				#反馈选项：
				[{{"desc":"点赞","type":"REACTION","id":"1287703867416379392"}},{{"desc":"爱心","type":"REACTION","id":"1287703867416379393"}},{{"desc":"难过","type":"REACTION","id":"1287703867416379394"}},{{"desc":"开心","type":"REACTION","id":"1287703867416379395"}},{{"desc":"惊讶","type":"REACTION","id":"1287703867416379396"}},{{"desc":"生气","type":"REACTION","id":"1287703867416379397"}},{{"desc":"你温柔浅笑勾引","type":"GIF","id":"1287703867416379398"}},{{"desc":"你抬头微笑","type":"GIF","id":"1287703867416379399"}},{{"desc":"你转身转头眨眼","type":"GIF","id":"1287703867416379400"}},{{"desc":"你双手捧在胸前表达想念","type":"GIF","id":"1287703867416379401"}},{{"desc":"你往前一步做出鬼脸","type":"BUBBLE","id":"1287703867416379402"}},{{"desc":"你转身发了一个wink","type":"BUBBLE","id":"1287703867416379403"}},{{"desc":"你摆手打招呼说hi","type":"BUBBLE","id":"1287703867416379404"}}]
				
				#反馈选项优先级 
				BUBBLE > GIF > REACTION
				
				#返回格式：JSON
				注意不要直接回复一个字符串！按以下要求来
				举例：{{"fbOptionID":1}} 或者 {{"fbOptionID":null}}
				""";
		List<MessageTextDTO> messages=new ArrayList<>();
		MessageTextDTO cm=new MessageTextDTO();
		cm.setRole(MessageRoleEnum.USER.name().toLowerCase());
		cm.setContent(systemPrompt);
//		messages.add(0, cm);
//		cm=new ChatMessageDTO();
//		cm.setRole(ChatMessageRoleEnum.ASSISTANT.name().toLowerCase());
//		cm.setContent("hi");
//		messages.add(1, cm);
//		cm=new ChatMessageDTO();
//		cm.setRole(ChatMessageRoleEnum.USER.name().toLowerCase());
//		cm.setContent("无聊");
		messages.add(cm);
		
		WenxinHandler wh=new WenxinHandler();
		wh.url="https://aip.baidubce.com";
		wh.apiKey="LVScr2Z4igKyG1gm6A89rAyl";
		wh.secretKey="YdfGbuETzj1YSIa9IWWGUpGPetd1ef62";
		
//		WxChatCompletionsAO ao1=wh.getRequestParam("123456", messages);
		ChatCompletionsBO<MessageTextDTO> param=new ChatCompletionsBO<>();
		param.setMessages(messages);
		System.out.println(wh.execute(param));
//		wh.execute(param,(s)->{
//			System.out.println(s);
//		},(s)->{
//			System.out.println(s);
//		});
	}
	
}
